package com.gbase8c.dmt.db.metadata;

import com.gbase8c.dmt.common.exception.MetadataException;
import com.gbase8c.dmt.model.enums.DbType;
import com.gbase8c.dmt.model.migration.dto.DataSourceDto;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Constructor;

@Slf4j
public class MetadataFactory {

    public static Metadata getMetaData(DataSourceDto dto) {
        Metadata metadata;
        String metadataClass = metadataClass(dto);
        try {
            Class<?> clazz = Class.forName(metadataClass);
            Constructor<?> constructor = clazz.getConstructor(DataSourceDto.class);
            metadata = (Metadata) constructor.newInstance(dto);
        } catch (Exception e) {
            log.error("获取数据源metadata出错!", e);
            throw MetadataException.asMetadataException("获取数据源metadata出错!", e);
        }
        return metadata;
    }

    private static String metadataClass(DataSourceDto dto) {
        String metadataClass;
        DbType.DbVersion dbVersion = dto.getDbVersion();
        if (dbVersion.getMetadataClass() != null) {
            metadataClass = dbVersion.getMetadataClass();
        } else {
            metadataClass = dto.getDbType().getMetadataClass();
        }
        return metadataClass;
    }

}